package cn.iocoder.yudao.module.erp.service.purpurchaseorder;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.QueryWrapperX;
import cn.iocoder.yudao.module.erp.controller.admin.purpurchaseorder.vo.PurPurchaseOrderPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.purpurchaseorder.vo.PurPurchaseOrderRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.purpurchaseorder.vo.PurPurchaseOrderSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purpurchaseorder.PurPurchaseOrderDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purpurchaseorderitem.PurPurchaseOrderItemDO;
import cn.iocoder.yudao.module.erp.dal.mysql.invoicechecklistitem.InvoiceCheckListItemMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.pristock.PriStockMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.purpurchaseorder.PurPurchaseOrderMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.purpurchaseorderitem.PurPurchaseOrderItemMapper;
import cn.iocoder.yudao.module.erp.dal.redis.no.ErpNoRedisDAO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.PUR_PURCHASE_CHECK_NO_EXISTS;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.PUR_PURCHASE_ORDER_NOT_EXISTS;

/**
 * ERP 采购单 Service 实现类
 * @author ls
 */
@Service
@Validated
public class PurPurchaseOrderServiceImpl implements PurPurchaseOrderService {

    @Resource
    private PurPurchaseOrderMapper purPurchaseOrderMapper;
    @Resource
    private PurPurchaseOrderItemMapper purPurchaseOrderItemMapper;
    @Resource
    private PriStockMapper PriStockMapper;
    @Autowired
    private InvoiceCheckListItemMapper invoiceCheckListItemMapper;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private AdminUserMapper adminUserMapper;
    @Resource
    private ErpNoRedisDAO noRedisDAO;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createPurPurchaseOrder(PurPurchaseOrderSaveReqVO createReqVO) {
        // 插入
        PurPurchaseOrderDO purPurchaseOrder = BeanUtils.toBean(createReqVO, PurPurchaseOrderDO.class);
        // 生成订单编号CGDD+日期
        String no = noRedisDAO.generate(ErpNoRedisDAO.PURPURCHASEOEDER_ORDER_NO_PREFIX);
        if (purPurchaseOrderMapper.selectByNo(no) != null) {
            throw exception(PUR_PURCHASE_CHECK_NO_EXISTS);
        }
        // 插入从单
        purPurchaseOrderMapper.insert(purPurchaseOrder.setPurchaseOrderId(no));
        // 修改主表状态
        purPurchaseOrderMapper.updateById(new PurPurchaseOrderDO().setId(purPurchaseOrder.getMainOrderId()).setIsMainOrder(1));
        // 插入子表
        createPurPurchaseOrderItemList(purPurchaseOrder.getId(), createReqVO.getPurPurchaseOrderItems());
        // 返回
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePurPurchaseOrder(PurPurchaseOrderSaveReqVO updateReqVO) {
        // 校验存在
        validatePurPurchaseOrderExists(updateReqVO.getId());
        // 更新
        PurPurchaseOrderDO updateObj = BeanUtils.toBean(updateReqVO, PurPurchaseOrderDO.class);
        purPurchaseOrderMapper.updateById(updateObj);

        // 更新子表
        updatePurPurchaseOrderItemList(updateReqVO.getId(), updateReqVO.getPurPurchaseOrderItems());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCountPurPurchaseOrder(PurPurchaseOrderSaveReqVO updateReqVO) {
        // 校验存在
        validatePurPurchaseOrderExists(updateReqVO.getId());

        // 检查子项列表是否为空
        if (updateReqVO.getPurPurchaseOrderItems() == null || updateReqVO.getPurPurchaseOrderItems().isEmpty()) {
            return;
        }
        // 更新子表
        List<PurPurchaseOrderItemDO> purPurchaseOrderItemDOList = purPurchaseOrderItemMapper.selectListByPurchaseOrderId(updateReqVO.getId());
        // 遍历purPurchaseOrderItemDOList和updateReqVO.getPurPurchaseOrderItems()，如果id相同则保存进新集合  将updateReqVO.getPurPurchaseOrderItems()中的countIn和countOut的值set到purPurchaseOrderItemDOList中
        List<PurPurchaseOrderItemDO> updatePurPurchaseOrderItemDOList =
                purPurchaseOrderItemDOList.stream().filter(item ->
                        updateReqVO.getPurPurchaseOrderItems().stream().anyMatch(item1 -> item1.getProductId().equals(item.getProductId()))).collect(Collectors.toList());
    for (PurPurchaseOrderItemDO item : updatePurPurchaseOrderItemDOList) {
        for (PurPurchaseOrderItemDO item1 : updateReqVO.getPurPurchaseOrderItems()) {
            if (item.getProductId().equals(item1.getProductId())) {
                item.setCountIn(item1.getCountIn()).setCountOut(item1.getCountOut());
                break;
            }
        }
    }
        purPurchaseOrderItemMapper.updateBatch(updatePurPurchaseOrderItemDOList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePurPurchaseOrder(String id) {
        // 校验存在
        validatePurPurchaseOrderExists(id);
        // 删除
        purPurchaseOrderMapper.deleteById(id);

        // 删除子表
        deletePurPurchaseOrderItemByPurchaseOrderId(id);
    }

    private void validatePurPurchaseOrderExists(String id) {
        if (purPurchaseOrderMapper.selectById(id) == null) {
            throw exception(PUR_PURCHASE_ORDER_NOT_EXISTS);
        }
    }

    @Override
    public PurPurchaseOrderDO getPurPurchaseOrder(String id) {
        return purPurchaseOrderMapper.selectById(id);
    }

    @Override
    public PageResult<PurPurchaseOrderDO> getPurPurchaseOrderPage(PurPurchaseOrderPageReqVO pageReqVO) {
        AdminUserRespDTO user = adminUserApi.getUser(getLoginUserId());

        return purPurchaseOrderMapper.selectPage(pageReqVO);
    }

    // ==================== 子表（ERP 采购单项） ====================

    @Override
    public List<PurPurchaseOrderItemDO> getPurPurchaseOrderItemListByPurchaseOrderId(String purchaseOrderId) {
        List<PurPurchaseOrderItemDO> purPurchaseOrderItemDOS = purPurchaseOrderItemMapper.selectListByPurchaseOrderId(purchaseOrderId);
//        把purPurchaseOrderItemDOS中的productName 拼接上规格productStandards
        for (PurPurchaseOrderItemDO purPurchaseOrderItemDO : purPurchaseOrderItemDOS) {
            String productName = purPurchaseOrderItemDO.getProductName();
            String productStandards = purPurchaseOrderItemDO.getProductStandards();
            if (productStandards != null) {
                productName = productName + "(" + productStandards + ")";
            }
            purPurchaseOrderItemDO.setProductName(productName);
        }
        return purPurchaseOrderItemDOS;
    }



    private void createPurPurchaseOrderItemList(String purchaseOrderId, List<PurPurchaseOrderItemDO> list) {
        list.forEach(o -> o.setPurchaseOrderId(purchaseOrderId.toString()));
        purPurchaseOrderItemMapper.insertBatch(list);
    }

    private void updatePurPurchaseOrderItemList(String purchaseOrderId, List<PurPurchaseOrderItemDO> list) {
        deletePurPurchaseOrderItemByPurchaseOrderId(purchaseOrderId);
		list.forEach(o -> o.setId(null).setUpdater(null).setUpdateTime(null)); // 解决更新情况下：1）id 冲突；2）updateTime 不更新
        createPurPurchaseOrderItemList(purchaseOrderId, list);
    }

    private void deletePurPurchaseOrderItemByPurchaseOrderId(String purchaseOrderId) {
        purPurchaseOrderItemMapper.deleteByPurchaseOrderId(purchaseOrderId);
    }

    /**
     * 根据审核单编号查询采购单
     * @param checkInvoiceId
     * @return
     */
    @Override
    public List<PurPurchaseOrderRespVO> getPurPurchaseOrderByCheckInvoiceId(String checkInvoiceId) {
//        根据发票整合单编号查询采购单
        List<PurPurchaseOrderDO> orderIntegrateId = purPurchaseOrderMapper.selectList(new QueryWrapperX<PurPurchaseOrderDO>().eq("order_integrate_id", checkInvoiceId));
        if (orderIntegrateId.isEmpty()){
            return null;
        }

//        设置创建者名
        List<String> creatorList = orderIntegrateId.stream().map(PurPurchaseOrderDO::getCreator).collect(Collectors.toList());
        List<AdminUserDO> adminUserDOS = adminUserMapper.selectList(new QueryWrapper<AdminUserDO>().in("id", creatorList));
        adminUserDOS.stream().collect(Collectors.toMap(user -> String.valueOf(user.getId()), AdminUserDO::getNickname));
        orderIntegrateId.forEach(o -> o.setCreator(adminUserDOS.get(creatorList.indexOf(o.getCreator())).getNickname()));

        return BeanUtils.toBean(orderIntegrateId, PurPurchaseOrderRespVO.class);

    }

    @Override
    public List<PurPurchaseOrderDO> getPurPurchaseOrderByOrderIntegrateId(String orderIntegrateId) {
        return purPurchaseOrderMapper.getPurPurchaseOrderByOrderIntegrateId(orderIntegrateId);
    }



}